from private_website.apps.app01 import models
from tools.const import TOKEN_TIME
import hashlib
from rest_framework.response import Response
import random
import datetime
import os


# Create your views here.
def get_pic_name(name: str):
    pic = '.' + name.split('.')[-1]
    data = str(random.randint(1000, 10000)) + name
    data = hashlib.md5(data.encode('utf-8')).hexdigest()
    return data[:20] + pic


def auth_token(func):
    def wrapper(*args, **kwargs):
        request = args[1]
        token = request.META.get('HTTP_TOKEN')
        if not models.Token.objects.filter(token=token):
            print('该账号没登录')
            return Response({'code': '300', 'msg': '该账号尚未登录'})
        else:
            obj = models.Token.objects.filter(token=token).first()
            if obj.outTime:
                return Response({'code': '300', 'msg': '该账号登录信息已过期或未登录'})
            else:
                end_time = obj.update_time + datetime.timedelta(days=TOKEN_TIME)
                end_time = end_time.replace(tzinfo=None)
                if datetime.datetime.now() > end_time:
                    return Response({'code': '300', 'msg': '该账号登录信息已过期'})
        return func(*args, **kwargs)
    return wrapper


def get_favorite_id(username: str, favorite, pk):
    if favorite is None:
        favorite = -1
    data = username + str(favorite) + str(pk)
    data = hashlib.md5(data.encode('utf-8')).hexdigest()[:12]
    return data


def delete_dir(path):
    if not os.path.exists(path):
        return False
    if os.path.isdir(path):
        file = os.listdir(path)
        for i in file:
            i = os.path.join(path, i)
            delete_dir(i)
        os.rmdir(path)
    else:
        os.remove(path)
    return True


class TokenFun(object):
    def __init__(self, user_obj):
        self.obj = user_obj

    def logout(self):
        if models.Token.objects.filter(user=self.obj):
            models.Token.objects.filter(user=self.obj).update(outTime=True)

    def login(self):
        data = self.obj.username + str(random.randint(1000, 10000))
        token = hashlib.md5(data.encode('utf-8')).hexdigest()
        if models.Token.objects.filter(user=self.obj):
            models.Token.objects.filter(user=self.obj).update(token=token,
                                                              update_time=datetime.datetime.now(),
                                                              outTime=0)
        else:
            models.Token.objects.create(token=token, user=self.obj)
        return token




